今天是紀錄LeetCode解題的第六天
第六題題目:
給一個字串假設是"PAYPALISHIRING",把它以Z字形排列輸出成"PAHNAPLSIIGYIR"
根據範例一的numRows=3,我們知道要存成三列,每當cur_row=0、1(在第一、二列時)我們要將下一個字元放在下一列,當cur_row=2(在第三列)時,要將下一個字元放回上一列,也就是說碰到0邊界就往下一列存放直到碰到numRows邊界就返回上一列存放
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
result = [""] * numRows
cur_row = 0
going_down = False
for c in s:
result[cur_row] += c
if cur_row == 0 or cur_row == numRows - 1:
going_down = not going_down
cur_row += 1 if isreverse else -1
return "".join(result)
初始狀態
s = "PAYPALISHIRING"
numRows = 3
rows = ['', '', ''] (每列是一個空字串)
cur_row = 0 (從第一行開始)
going_down = False
第一次執行
第二次執行
第三次執行
第四次執行
依此類推最後會得到rows = ['PAHN','APLSIIG','YIR'],接著合併回傳就是答案了